package com.easondongh.business.controller;

import com.easondongh.business.domain.GoodsSales;
import com.easondongh.business.domain.GoodsSalesback;
import com.easondongh.business.service.GoodsSalesService;
import com.easondongh.business.service.GoodsSalesbackService;
import com.easondongh.business.vo.GoodsSalesBackQueryVo;
import com.easondongh.common.enums.ResponseEnum;
import com.easondongh.common.response.ResponseObj;
import com.easondongh.common.vo.BasePageQueryVo;
import com.easondongh.common.vo.PageResult;
import com.easondongh.system.domain.SysUser;
import com.easondongh.common.shiro.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author EasonDongH
 * @date 2020/6/8 16:41
 */
@Slf4j
@RestController
@RequestMapping("/goodsSalesBack")
public class GoodsSalesBackController {

    @Autowired
    private GoodsSalesbackService goodsSalesbackService;
    @Autowired
    private GoodsSalesService goodsSalesService;

    @PostMapping("/processGoodsBack")
    public ResponseObj processGoodsBack(@RequestBody GoodsSalesback goodsSalesback) {
        if(goodsSalesback == null || goodsSalesback.getSalesId() == null || goodsSalesback.getGoodsId() == null) {
            log.warn("商品退货时：销售id、商品id不能为空");
            return new ResponseObj(ResponseEnum.GOODS_BACK_FAIL);
        }
        GoodsSales goodsSales = this.goodsSalesService.getById(goodsSalesback.getSalesId());
        if(goodsSales.getNumber() < goodsSalesback.getNumber()) {
            return new ResponseObj(ResponseEnum.GOODS_BACK_NUMER_INVALID);
        }
        SysUser loginUser = ShiroUtils.getCurrentLoginUser();
        goodsSalesback.setPayType(goodsSales.getPayType());
        goodsSalesback.setSalebackPrice(Double.parseDouble(goodsSales.getSalesPrice().toString()));
        goodsSalesback.setSalesbackTime(new Date());
        goodsSalesback.setOperatePerson(loginUser.getName());
        this.goodsSalesbackService.processGoodsBack(goodsSalesback);
        return new ResponseObj(ResponseEnum.GOODS_BACK_SUCCESS);
    }

    @PostMapping("/getByPage")
    public ResponseObj<PageResult<GoodsSalesback>> getByPage(@RequestBody BasePageQueryVo<GoodsSalesBackQueryVo> queryCondition) {
        if(queryCondition == null) {
            return ResponseObj.QueryFail;
        }
        PageResult<GoodsSalesback> result = this.goodsSalesbackService.getByPage(queryCondition);
        return new ResponseObj<>(ResponseEnum.QUERY_SUCCESS, result);
    }
}
